from flask import Flask, request, jsonify, Response, render_template, make_response, redirect
import json
import chromadb
from chromadb.utils import embedding_functions

# 创建flask对象
app = Flask(__name__)


@app.route('/vdb/', methods=['GET','POST'])
def respond_vdb():
    # chroma_client = chromadb.Client()
    # 获取请求中的value值
    # 接收处理json数据请求
    # data = json.loads(request.data)  # 将json字符串转为dict
    # value = data['value']
    # num = data['num']

    # 接收post请求的form表单数据
    value = request.form.get('value')
    num = int(request.form.get('num'))
    # 连接远程chromadb库
    chroma_client = chromadb.HttpClient("192.168.22.101", 8000)

    collection = chroma_client.get_or_create_collection(name="my_collection")
    # 执行该代码时下载了向量化模型，之后运行可以直接使用该模型速度也会很快
    # collection.add(
    #     documents=["哈利波特睡着了", "哈利猛的转身", "宇动源数字"],
    #     metadatas=[{"source": "my_source"}, {"source": "my_source"}, {"source": "my_source"}],
    #     ids=["id1", "id2", "id3"]
    # )
    results = collection.query(
        query_texts=[value],
        n_results=num
    )
    return results


#响应的几种方式
@app.route('/post_test')
def post_test():
    # 1、直接返回字符串
    return "do post test"

    # 2、模板渲染
    # return render_template('index.html',name='zhangsan')

    # 返回json
    # data = {'name':'zhangsan','age':12}
    # return jsonify(data)

    # 自定义response对象
    # html = render_template('index.html',name='zhangsan')
    # res = make_response(html)
    # return res


# 重定向
@app.route('/redirect/')
def make_redirect():
    pass
    # 1、直接写地址
    return redirect('httops://www.baidu.com')

    # 2、使用项目中的路由
    # return redirect('/post_test/')

@app.route('/')
def home():
    return "hello_flask"


if __name__ == '__main__':
    app.run(port=5000, host='0.0.0.0')
